package org.com.ashen.service.util;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.com.ashen.common.exception.BusinessException;
import org.com.ashen.common.exception.ErrorEnum;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class ResultSetToJson {
	public static String convertResultSetToJson(ResultSet rs) {
		JSONArray array = new JSONArray();
		ResultSetMetaData metaData;
		try {
			metaData = (ResultSetMetaData) rs.getMetaData();
			int columnCount = metaData.getColumnCount();
			while (rs.next()) {
				JSONObject jsonObject = new JSONObject();
				for (int i = 1; i <= columnCount; i++) {
					String columnName = metaData.getColumnLabel(i);
					String value = rs.getString(columnName);
					jsonObject.put(columnName, value);
				}
				array.add(jsonObject);
			}
			return array.toJSONString();
		} catch (SQLException e) {
			throw new BusinessException(ErrorEnum.SESSIONID_ERROR);
		}
	}
	
	
	public static String convertResultSetToTable(ResultSet rs) {
		ResultSetMetaData metaData;
		try {
			metaData = (ResultSetMetaData) rs.getMetaData();
			int columnCount = metaData.getColumnCount();
			String result = "";
			while (rs.next()) {
				for (int i = 1; i <= columnCount; i++) {
					String columnName = metaData.getColumnLabel(i);
					String value = rs.getString(columnName);
					if (value == null) {
						value = "";
					}
					if (i != columnCount) {
						result += value+"\t";
					}else {
						result += value;
					}
				}
				result += "\r\n";
			}
			if (result != "") {
				result = result.substring(0, result.length()-2);
			}
			return result;
		} catch (SQLException e) {
			throw new BusinessException(ErrorEnum.SESSIONID_ERROR);
		}
		
		
	}
}
